import { userLogin, logout, getUserInfo, phoneLogin } from '@/api/user'
import { resetRouter } from '@/router'
import $storage from '@/utils/storage.js'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: $storage.getUserToken(),
    name: '',
    avatar: '',
    info: {},
    roles: [],
    level: null,
    btnMenus: [],
    funMenus: [],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_INFO: (state, info) => {
    state.info = info
  },
  SET_FUN_MENUS: (state, funMenus) => {
    state.funMenus = funMenus
  },
  SET_BTN_MENUS: (state, btnMenus) => {
    state.btnMenus = btnMenus
  },
  SET_USER_LEVEL:(state, level)=> {
    state.level = level
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      userLogin({ username: username.trim(), password: password }).then(response => {
        console.log(response)
        const { code, data, message } = response
        if (code !== 200) {
          Message.error(message)
          throw message
        }
        commit('SET_TOKEN', data.token)
        $storage.setUserToken(data.token)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // phone lohin
  phone({ commit }, userInfo) {
    const { phone, code } = userInfo
    return new Promise((resolve, reject) => {
      phoneLogin({ phone: phone, code: code }).then(response => {
        console.log(response)
        const { code, data, message } = response
        if (code !== 200) {
          Message.error(message)
          throw message
        }
        commit('SET_TOKEN', data.token)
        $storage.setUserToken(data.token)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const { data } = response
        console.log(data)
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roleVos: roles, menuVos: funMenus, buttonVos: btnMenus, username: name, headImage: avatar, userLevel: level } = data

        // roles must be a non-empty array
        if ((!roles || roles.length <= 0) && (!level || level === 1)) {
          reject('抱歉，你没有权限访问系统')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_INFO', data)
        commit('SET_AVATAR', avatar)
        commit('SET_FUN_MENUS', funMenus)
        commit('SET_BTN_MENUS', btnMenus)
        commit('SET_USER_LEVEL', level)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        $storage.removeUserToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      $storage.removeUserToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

